/* ========================================
   主题系统 JavaScript
   ======================================== */

// 主题配置
const THEMES = [
    { id: 'default', name: '默认蓝', color: '#007bff' },
    { id: 'purple', name: '深邃紫', color: '#6f42c1' },
    { id: 'emerald', name: '翡翠绿', color: '#10b981' },
    { id: 'rose', name: '晨曦粉', color: '#e11d48' },
    { id: 'sky', name: '天空蓝', color: '#0ea5e9' },
    { id: 'orange', name: '橙色日落', color: '#f97316' },
    { id: 'cyan', name: '青色水波', color: '#06b6d4' },
    { id: 'violet', name: '紫罗兰', color: '#8b5cf6' },
    { id: 'fuchsia', name: '品红', color: '#d946ef' },
    { id: 'amber', name: '琥珀金', color: '#f59e0b' },
    { id: 'slate', name: '石板灰', color: '#475569' },
    { id: 'forest', name: '森林绿', color: '#15803d' },
    { id: 'ocean', name: '深海蓝', color: '#1e40af' },
    { id: 'sakura', name: '樱花粉', color: '#ec4899' },
    { id: 'mint', name: '薄荷绿', color: '#14b8a6' },
    { id: 'crimson', name: '深红', color: '#dc2626' },
    { id: 'indigo', name: '靛蓝', color: '#4f46e5' },
    { id: 'lime', name: '石灰绿', color: '#65a30d' },
    { id: 'rosegold', name: '玫瑰金', color: '#b45309' },
    { id: 'midnight', name: '午夜黑', color: '#1f2937' }
];

// 当前主题
let currentTheme = localStorage.getItem('app-theme') || 'default';

// 初始化主题系统
function initTheme() {
    // 应用保存的主题
    applyTheme(currentTheme);
    
    // 创建主题选择器UI
    createThemeSelector();
    
    // 绑定事件
    bindThemeEvents();
}

// 应用主题
function applyTheme(themeId) {
    console.log('应用主题:', themeId);
    document.documentElement.setAttribute('data-theme', themeId);
    currentTheme = themeId;
    localStorage.setItem('app-theme', themeId);
    
    // 强制重绘
    document.body.style.display = 'none';
    document.body.offsetHeight; // 触发重排
    document.body.style.display = '';
    
    // 更新主题选择器中的激活状态
    updateThemeSelector();
    
    console.log('主题已应用，当前data-theme属性:', document.documentElement.getAttribute('data-theme'));
}

// 创建主题选择器UI
function createThemeSelector() {
    const selectorHTML = `
        <div class="theme-selector">
            <button class="theme-toggle-btn" id="themeToggleBtn" title="切换主题">
                <i class="bi bi-palette-fill"></i>
            </button>
            <div class="theme-panel" id="themePanel">
                <div style="font-weight: 600; margin-bottom: 10px; color: var(--text-primary);">
                    <i class="bi bi-palette me-2"></i>选择主题
                </div>
                <div class="theme-grid" id="themeGrid">
                    ${THEMES.map(theme => `
                        <div class="theme-option-wrapper">
                            <div class="theme-option ${theme.id === currentTheme ? 'active' : ''}" 
                                 data-theme-id="${theme.id}"
                                 style="background: linear-gradient(135deg, ${theme.color} 0%, ${adjustColor(theme.color, -20)} 100%);"
                                 title="${theme.name}">
                            </div>
                            <div class="theme-option-label">${theme.name}</div>
                        </div>
                    `).join('')}
                </div>
            </div>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', selectorHTML);
}

// 绑定主题相关事件
function bindThemeEvents() {
    // 切换主题面板
    const toggleBtn = document.getElementById('themeToggleBtn');
    const panel = document.getElementById('themePanel');
    
    toggleBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        panel.classList.toggle('show');
    });
    
    // 点击外部关闭面板
    document.addEventListener('click', (e) => {
        if (!e.target.closest('.theme-selector')) {
            panel.classList.remove('show');
        }
    });
    
    // 选择主题
    const themeOptions = document.querySelectorAll('.theme-option');
    themeOptions.forEach(option => {
        option.addEventListener('click', () => {
            const themeId = option.getAttribute('data-theme-id');
            applyTheme(themeId);
            
            // 显示提示
            showThemeToast(`已切换到 ${THEMES.find(t => t.id === themeId).name} 主题`);
        });
    });
}

// 更新主题选择器激活状态
function updateThemeSelector() {
    const themeOptions = document.querySelectorAll('.theme-option');
    themeOptions.forEach(option => {
        const themeId = option.getAttribute('data-theme-id');
        if (themeId === currentTheme) {
            option.classList.add('active');
        } else {
            option.classList.remove('active');
        }
    });
}

// 调整颜色亮度
function adjustColor(color, percent) {
    const num = parseInt(color.replace('#', ''), 16);
    const amt = Math.round(2.55 * percent);
    const R = (num >> 16) + amt;
    const G = (num >> 8 & 0x00FF) + amt;
    const B = (num & 0x0000FF) + amt;
    return '#' + (
        0x1000000 +
        (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000 +
        (G < 255 ? G < 1 ? 0 : G : 255) * 0x100 +
        (B < 255 ? B < 1 ? 0 : B : 255)
    ).toString(16).slice(1);
}

// 显示主题切换提示
function showThemeToast(message) {
    // 使用现有的通知系统
    if (typeof showNotification === 'function') {
        showNotification(message, 'success');
    } else {
        // 简单的提示
        const toast = document.createElement('div');
        toast.className = 'toast-message';
        toast.textContent = message;
        toast.style.cssText = `
            position: fixed;
            top: 70px;
            right: 20px;
            background: var(--primary-color);
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 9999;
            animation: slideInRight 0.3s ease;
        `;
        document.body.appendChild(toast);
        
        setTimeout(() => {
            toast.style.animation = 'slideOutRight 0.3s ease';
            setTimeout(() => toast.remove(), 300);
        }, 2000);
    }
}

// 移动端菜单控制
function initMobileMenu() {
    // 创建遮罩层
    if (!document.querySelector('.sidebar-overlay')) {
        const overlay = document.createElement('div');
        overlay.className = 'sidebar-overlay';
        document.body.appendChild(overlay);
    }
    
    // 汉堡菜单按钮事件
    const menuBtn = document.getElementById('mobileMenuBtn');
    const sidebar = document.querySelector('.sidebar');
    const overlay = document.querySelector('.sidebar-overlay');
    
    if (menuBtn && sidebar && overlay) {
        // 打开菜单
        menuBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            sidebar.classList.add('show');
            overlay.classList.add('show');
        });
        
        // 点击遮罩关闭菜单
        overlay.addEventListener('click', () => {
            sidebar.classList.remove('show');
            overlay.classList.remove('show');
        });
        
        // 点击菜单项后关闭菜单（跳转到新页面）
        const navLinks = sidebar.querySelectorAll('.nav-link');
        navLinks.forEach(link => {
            link.addEventListener('click', (e) => {
                if (window.innerWidth <= 768) {
                    // 只有在实际跳转时才关闭菜单
                    // 如果是退出登录按钮，让它的onclick处理
                    if (!link.getAttribute('onclick')) {
                        setTimeout(() => {
                            sidebar.classList.remove('show');
                            overlay.classList.remove('show');
                        }, 100);
                    }
                }
            });
        });
    }
}

// 自动调整视口高度（解决移动端地址栏问题）
function setMobileViewportHeight() {
    const vh = window.innerHeight * 0.01;
    document.documentElement.style.setProperty('--vh', `${vh}px`);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    initTheme();
    initMobileMenu();
    setMobileViewportHeight();
});

// 窗口大小改变时重新计算
window.addEventListener('resize', setMobileViewportHeight);

// 导出函数供其他脚本使用
window.ThemeManager = {
    applyTheme,
    currentTheme: () => currentTheme,
    themes: THEMES
};
